<!--
 * @Author: shenya
 * @Date: 2023-09-08 10:42:49
 * @Description: 编辑分类dialog
-->
<template>
  <el-dialog
    title="编辑"
    :visible.sync="visible"
    width="50%"
    append-to-body
  >
    <avue-form
      ref="editform"
      v-model="form"
      :option="formOption"
    ></avue-form>
    <template #footer>
      <el-button
        type="primary"
        :loading="loading"
        @click="submit"
      >
        提交
      </el-button>
      <el-button @click="visible = false">取消</el-button>
    </template>
  </el-dialog>
</template>
<script>
import { formOption } from '@/const/crud/community-content/topic';
import { seletTopicById, updateTopic } from '@/api/core/topic';
export default {
  props: {
    value: {
      type: Boolean,
      default: false,
    },
    action: {
      type: String,
    },
    id: {
      type: String,
    },
  },
  data() {
    return {
      form: {},
      loading: false,
    };
  },
  computed: {
    visible: {
      get() {
        return this.value;
      },
      set(val) {
        this.$emit('input', val);
      },
    },
    formOption() {
      return formOption(this.action === 'edit');
    },
  },
  watch: {
    visible(val) {
      if (val) {
        this.selectTopic();
      } else {
        this.$refs.editform.resetFields();
      }
    },
  },
  methods: {
    selectTopic() {
      seletTopicById(this.id).then((res) => {
        this.form = res.data.data;
      });
    },
    //提交
    submit() {
      this.$refs['editform'].validate((valid, done) => {
        if (valid) {
          const params = {
            id: this.id,
            name: this.form.name,
            sort: this.form.sort,
            content: this.form.content,
            hideFlag: this.form.hideFlag,
          };
          updateTopic(params)
            .then((res) => {
              if (!res.data) return;
              this.$emit('success');
              done();
              this.visible = false;
              this.loading = false;
              this.$message.success('修改成功！');
            })
            .catch((err) => {
              done();
              this.loading = false;
              throw new Error(err);
            });
        }
      });
    },
  },
};
</script>
<style lang="scss" scoped></style>
